﻿/**
 * 继承Acitivity
 * 所有显示类的父类
 * */

package com.bankcomm.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;
import org.keplerproject.luajava.LuaException;
import org.keplerproject.luajava.LuaObject;
import org.xml.sax.SAXException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.EditText;
import bocom.mobile.usbkey.IMobile;

import com.bankcomm.R;
import com.bankcomm.audio.AudioServerManager;
import com.bankcomm.common.ConfigManager;
import com.bankcomm.common.LPMid;
import com.bankcomm.luafuction.LuaHistory;
import com.bankcomm.luafuction.LuaLib;
import com.bankcomm.luafuction.LuaTimer;
import com.bankcomm.luafuction.LuaWindow;
import com.bankcomm.ui.specialwidget.LPButton;
import com.bankcomm.ui.specialwidget.LPCityChooser;
import com.bankcomm.ui.specialwidget.LPDigitPasswordTextField;
import com.bankcomm.ui.specialwidget.LPHidden;
import com.bankcomm.ui.specialwidget.LPLottery;
import com.bankcomm.ui.specialwidget.LPMovieTicket;
import com.bankcomm.util.BOCKeyMobile;
import com.bankcomm.util.BitmapZxingResouce;
import com.bankcomm.util.BranchBankUtils;
import com.bankcomm.zxing.CaptureActivity;
import com.bankcomm.zxing.decoding.DecodeFormatManager;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.crypto.Base64;
import com.rytong.tools.crypto.Constant;
import com.rytong.tools.crypto.DESCipher;
import com.rytong.tools.crypto.HMac;
import com.rytong.tools.crypto.hsmcli;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.httpconnect.WaitDialog.Task;
import com.rytong.tools.ui.AtomParser;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.Component.CompositedComponent;
import com.rytong.tools.ui.ComponentCopy;
import com.rytong.tools.ui.LPCheckBox;
import com.rytong.tools.ui.LPDateField;
import com.rytong.tools.ui.LPImageItem;
import com.rytong.tools.ui.LPLabel;
import com.rytong.tools.ui.LPLayout;
import com.rytong.tools.ui.LPRadio;
import com.rytong.tools.ui.LPSegment;
import com.rytong.tools.ui.LPSegmentLayout;
import com.rytong.tools.ui.LPSelect;
import com.rytong.tools.ui.LPSwitchCopy;
import com.rytong.tools.ui.LPTextField;
import com.rytong.tools.ui.LPTextField.MyLPTextField;
import com.rytong.tools.ui.WaitProgressDialog;
import com.rytong.tools.utils.EventHandler;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

@SuppressWarnings("deprecation")
public class EMPView extends BaseViewCopy {
	// lua集合
	public static LuaLib lualib_;
	// 新加密码临时变量，保证一个form只用一次key和iv
	byte[] keyTemp_;
	byte[] ivTemp_;
	final public static String CERTIFICATE = "root_u.png";
	static public LPMid mid_;

	// 扫描完成直接提交
	static int SCAN_SUBMIT_CODE = 193114;
	// 扫描完成回显到文本框
	static int SCAN_RESHOW_CODE = 193115;
	//LUA点击后发送二维码
	static int SCAN_SEND_QRCODE_BY_GET=193116;
	static int IMAGE_PICKER_REQUEST_CODE = 0;

	public WaitProgressDialog waitProgress = null;
	private Handler handler = null;
	//qr扫描参数及提交url mod by z.b start
	protected String qrUrl;
	protected String qrParm;
	protected static final int CODE_QRBITMAP = 0;
	protected static final int CODE_TEMPIMAG = 1;
	protected static final int CODE_FAVIMAG = 2;  
	
	//基金新增搜索
	private String searchURL ;
	private String searchBODY;
	
	//mod by z.b end
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (null == savedInstanceState) {
			ConfigManager.currentView_ = this;
			if(null == handler){
				handler = new Handler();
			}
			String xml = "" ;
			xml = getIntent().getStringExtra("reply");
			initLuaScript();
			handleJarEvent();
			parserXMLToView(xml);
		}
	}
	
	/**
	 * 解析从上个页面返回的报文，生成view
	 * */
	public void parserXMLToView(String xml) {
		
//        xml=Utils.getStringFormAsset(this, "test1.xml");
		xml = Utils.unescapeHTML(xml);
		xml = Utils.insteadOfSpecillCharacter(xml, true);
		LuaHistory.add(xml);
		AtomParser apc = new AtomParser(this, AtomParser.ENTIRE);
		try {
			android.util.Xml.parse(xml, apc);
			// 有可能解析的报文不含body标签，导致COMPONENT为null，此处加一个判断。
			if(ComponentCopy.COMPONENT != null){
				setContentView(ComponentCopy.COMPONENT.getLPView());
			} else { // 否则抛出一个异常。
				throw new Exception();
			}
		} catch (SAXException e) {
			Utils.printException(e);
		} catch (Exception e){
			Utils.printException(e);
		}
	}

	
	/**
	 * 遍历界面控件，如果是按钮控件，且类型为submit，则执行以前的发送操作
	 * 
	 * @param o
	 */
	public void getSubmitButton() {
		// TODO Auto-generated method stub
		if (null == Component.VWIDGETARRAY)
			return;
		int size = Component.VWIDGETARRAY.size();
		Object com;
		LPButton button;
		String type;
		for (int i = 0; i < size; i++) {
			com = Component.VWIDGETARRAY.get(i);
			if (com instanceof LPButton) {
				button = (LPButton) com;
				if (button.isShown() && button.isFocused()) {
					type = (String) button.getPropertyByName("type");
					String bockey = button.getPropertyByName("bockey");
					if (null != type && type.equalsIgnoreCase("submit")) {
						if ("true".equals(bockey)) {
							// 获得隐藏域: 签名报文
							String data = getHidden();
						}
						submit(button);
						return;
					}
				}
			}
		}
	}
	
	/**
	 * 遍历界面控件，如果是隐藏域控件，且类型为hidden
	 * 
	 * @param o
	 */
	public String getHidden() {
		String result = null;
		
		// TODO Auto-generated method stub
		if (null == Component.VWIDGETARRAY)
			return null;
		int size = Component.VWIDGETARRAY.size();
		Object com;
		LPHidden lphd;
		String type;
		try {
			for (int i = 0; i < size; i++) {
				com = Component.VWIDGETARRAY.get(i);
				if (com instanceof LPHidden) {
					lphd = (LPHidden) com;
					type = (String) lphd.getPropertyByName("type");
					if (null != type && type.equalsIgnoreCase("hidden")) {
						String name = lphd.getPropertyByName("name");
						String value = lphd.getPropertyByName("value");
						if ("preSignInfo".equals(name)) {
							result = getBCSignMsg(value);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	// 转账报文
	private String getBCSignMsg(String value) {
		String result = null;
		try {
			result = "<?xml version=\"1.0\" encoding=\"utf-8\"?><signData>" + URLDecoder.decode(value, "UTF-8").replace("&lt;", "<").replace("&gt;", ">") + "</signData>";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	/**
	 * 遍历form控件作相应的一次一密，并发送数据
	 * 
	 * @param form2
	 */
	public void sendForm(final LPLayout form) {
        //密码键盘清空键值对
        mid_ = LPMid.getInstance() ;
        mid_.digitStr = null ;
        mid_.isNeedGetKey = false ;
//        mid_.num = null ;  //清空数字图形键盘键值对
//        mid_.letter = null ;
		// TODO Auto-generated method stub
		if (null == form)
			return;
		// 如果父控件为form控件，则获取其action值
		String action = (String) form.getPropertyByName("action");
		if (null == action || action.equals("")) {
			return;
		} else {
			//输入非空  控制
			String error = NotNuLLCtrl(form);
			Utils.printOutToConsole("错误信息: " + error);
			if (!"".equals(error)) {
				return;
			}

			
			// 防止后台接口不是以/开头的情况
			action = action.trim();
			if (!action.startsWith("/"))
				action = "/".concat(action);
			final String actionReal = action;
			// 如果当前有同步的任务，就不进行下面的操作了。
			if(Utils.SYN_SUBMIT_REQUEST_NUMBER_ > 0){
				return;
			} else {
				Utils.SYN_SUBMIT_REQUEST_NUMBER_++;
			}
			// 如果form存在action则执行界面遍历操作
			WaitDialog wd = new WaitDialog();
			wd.addFgTask(EMPView.this, null, 0, 0, 0, new WaitDialog.Task(0) {
				String reply = "";

				@Override
				public void run(WaitDialog dlg) throws Exception {
					// TODO Auto-generated method stub
					int size = form.getCompChildCount();
					Component comp = null;
					LPLayout lpl;
					StringBuffer buf = new StringBuffer(10);

					// 清空key和iv对，保证一个form提交有一对新的key和iv
					keyTemp_ = null;
					ivTemp_ = null;
					for (int i = 0; i < size; i++) {
//						comp = form.getChildAt(i);
						comp = form.getCompChildAt(i);
						// 控件如果不可见，则不提交它的相关值
						if (!(comp instanceof LPLabel)) {
							if (View.VISIBLE != comp.getVisibility()) {
								continue;
							}
						}
						if (comp instanceof LPLayout) {
							lpl = (LPLayout) comp;
							buf = getBuffFromFormLayout(lpl, buf, actionReal, this);
						} else {
							buf = getBuffFromForm(comp, buf, actionReal, this);
						}
					}

					String body = buf.toString();
					Utils.printOutToConsole(body);
					buf.delete(0, buf.length());
					buf = null;
                  
					String host = "";
					if (!actionReal.contains(ConfigManager.SERVER_URI_NO_PORT)) {
						host = ConfigManager.SERVER_URI.concat(actionReal);
						
					} else {
						host = actionReal;
						if(host.startsWith("/")){
							  host=host.substring(1,host.length());	
							}
					}
					
					reply = LPMid.getInstance().um_.handleShouldAES(host, body, this);
					reply = Utils.unescapeHTML(reply);
					reply = Utils.insteadOfSpecillCharacter(reply, true);
				}

				public void onSuccess(WaitDialog dlg) {
					EMPView.this.runOnUiThread(new Runnable() {

						@Override
						public void run() {
					        mid_.num = null ;  //清空数字图形键盘键值对，之所以放在这里清空图形键盘的键值对数组，不放在sendform开始时与mid_.digitStr一起清空
					        mid_.letter = null ;//是为了避免客户在点击submit后，点击返回取消submit，
							if(LPToastUtil.getInstance().isBranchBank){
								reply = BranchBankUtils.addBrAtEnd(BranchBankUtils.includeAloneAttribute(reply));
							}
								AtomParser apc = new AtomParser(EMPView.this, AtomParser.ENTIRE);
								try {
									android.util.Xml.parse(reply.trim(), apc);
									 String notstack=form.getPropertyByName("popStack");
							         if(!notstack.equals("")&& notstack.equals("true")){
							        	 Component.ACTIONV.pop();
							           }
									// 解析成功之后进行压栈。
									Component.ACTIONV.push(reply);
								} catch (Exception e) {
									Utils.printException(e);
								}
								Utils.SYN_SUBMIT_REQUEST_NUMBER_ = 0;
								// 有可能解析的报文不含body标签，导致COMPONENT为null，此处加一个判断。
								if(ComponentCopy.COMPONENT != null){
									setContentView(ComponentCopy.COMPONENT.getLPView());
								}
						}
					});
					super.onSuccess(dlg);
				}
				
				@Override
				public void onFailure(WaitDialog dlg) {
					super.onFailure(dlg);
					Utils.SYN_SUBMIT_REQUEST_NUMBER_ = 0;
					handleException(getErrMsg());
				}
			});
		}
	}

	protected StringBuffer getBuffFromFormLayout(LPLayout comp, StringBuffer buf, String action, Task task) {
//		int size = comp.getChildCount();
		int size = comp.getCompChildCount();
		Component temp;
		for (int i = 0; i < size; i++) {
//			temp = comp.getChildAt(i);
			temp = comp.getCompChildAt(i);
			if (temp.getVisibility() == View.VISIBLE) {
				if (temp instanceof LPLayout) {
					LPLayout lpl = (LPLayout) temp;
					buf = getBuffFromFormLayout(lpl, buf, action, task);
				} else {
					buf = getBuffFromForm(temp, buf, action, task);
				}
			} else {
				continue;
			}
		}
		return buf;
	}

	/**
	 * 该方法处理一次一密操作，如果有自定义的一次一密操作请在这里面修改
	 * 
	 * @param encryptMode
	 * @param value
	 * @param task
	 * @return
	 * @throws Exception
	 */
	String encryptValue(String encryptMode, String value, WaitDialog.Task task) throws Exception {
		String content = value;
		if (value == null || encryptMode == null || "".equalsIgnoreCase(encryptMode) ) {
			return value;
		}

		boolean needPasswordKey = false;
		if (encryptMode.equals("01")) {// 动态加密
			content = value;
			needPasswordKey = true;
		} else if (encryptMode.equals("A0")) {// APIN加密
			content = hsmcli.PkEncryptAPin(value);
		} else if (encryptMode.equals("A1")) {// APIN加密与动态加密
			content = hsmcli.PkEncryptAPin(value);
			needPasswordKey = true;
		} else if (encryptMode.equals("E0")) {// EPIN加密
			content = hsmcli.PkEncryptEPin(value);
		} else if (encryptMode.equals("E1")) {// EPIN加密与动态加密
			content = hsmcli.PkEncryptEPin(value);
			needPasswordKey = true;
		} else if (encryptMode.equals("AE0")) {// APIN、EPIN加密
			content = hsmcli.PkEncryptAPin(value) + hsmcli.PkEncryptEPin(value);
		} else if (encryptMode.equals("AE1")) {// APIN、EPIN加密与动态加密
			content = hsmcli.PkEncryptAPin(value) + hsmcli.PkEncryptEPin(value);
			needPasswordKey = true;
		}

		if (needPasswordKey && null == keyTemp_ && null == ivTemp_) {
			// ClientRandom
			byte[] cUnixTime = Utils.getClientGMTUnixTime();
			byte[] clientRandom = ClientHello.getClientRandom(28);
			byte[] RNC = new byte[32];
			System.arraycopy(cUnixTime, 0, RNC, 0, cUnixTime.length);
			System.arraycopy(clientRandom, 0, RNC, cUnixTime.length, clientRandom.length);
			String rncStr = Base64.encode(RNC);
			HttpManager hm = LPMid.getInstance().hm_;
			String body = "clientrandom=" + Utils.escapeURIComponent(rncStr);
			body = AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);
			String status = (String) hm.sendPostRequest(ConfigManager.SERVER_URI + ConfigManager.GET_ONESERCRET, body, task, null, null);
			if (status == null)
				throw new NullPointerException(Constant.ERR_ENCRYPT_SERVER_01);
			if (status.indexOf("<error") != -1) {
				String error = Utils.getXMLResponseAttribute(status, "string=\"", 0, Utils.MATCH);
				throw new Exception(error);
			}
			status = AESCipher.decrypt(status, AESCipher.serverKey_, AESCipher.serverIv_);
			String serverRandom = Utils.getXMLResponseAttribute(status, "serverrandom=\"", 0, Utils.MATCH);
			byte[] RNS = Base64.decodeToBytes(serverRandom);
			byte[] seed = new byte[RNC.length + RNS.length];
			System.arraycopy(RNC, 0, seed, 0, RNC.length);
			System.arraycopy(RNS, 0, seed, RNC.length, RNS.length);
			byte[] secret = HMac.PRF(ClientHello.PMS_, HMac.TLS_ONCE_SECRET_CONST(), seed, 48);
			byte[] key = ClientHello.getAESKey(secret);
			byte[] iv = ClientHello.getAESIv(secret);
			keyTemp_ = key;
			ivTemp_ = iv;
			byte[] data = AESCipher.encrypt(content.getBytes("UTF-8"), key, iv);
			content = Base64.encode(data);

		} else if (null != keyTemp_ && null != ivTemp_) {
			byte[] data = AESCipher.encrypt(content.getBytes("UTF-8"), keyTemp_, ivTemp_);
			content = Base64.encode(data);
		}
		return content;
	}
	
	private BOCKeyMobile keyMobile = new BOCKeyMobile(this);

	/**
	 * 如果按钮类型为submit，则还有可能需要进行一次一密的加密操作 1、获取最近一个form控件的action操作，这里面包含了需要提交的接口 2、遍历form控件，将需要加密的控件内容重新处理
	 * 
	 * @param button
	 */
	public void submit(Component component) {
		if (component instanceof LPButton) {
			LPButton button = (LPButton) component;
			if (button.isShown() && button.isFocused()) {
				String type = (String) button.getPropertyByName("type");
				String bockey = button.getPropertyByName("bockey");
				if (null != type && type.equalsIgnoreCase("submit")) {
					if ("true".equals(bockey)) {
						// 获取隐藏域: 签名报文
						String data = getHidden();
						// 获取密码长度
						String length = getPasswordLength();
						if (length.length() != 6) {
							LPToastUtil.getInstance().getToast(
									getString(R.string.password_length), this);
						} else {
							if (!"".equals(data) && null != data) {
								System.out.println("签名前---- >>>" + data);
								keyMobile.setComponent(component);
								keyMobile.open(data);
							} else {
								LPToastUtil.getInstance().getToast(
										getString(R.string.signdata), this);
							}
						}
					} else {
						sendForm(component.findparentForm(component));
					}
				}
			}
		} else {
			sendForm(component.findparentForm(component));
		}
	}
	
	/**
	 * 遍历界面控件，如果是隐藏域控件，且类型为hidden
	 * 
	 * @param o
	 */
	public String getPasswordLength() {
		String result = null;
		
		// TODO Auto-generated method stub
		if (null == Component.VWIDGETARRAY)
			return null;
		int size = Component.VWIDGETARRAY.size();
		Object com;
		LPDigitPasswordTextField lpdptf;
		String type;
		try {
			for (int i = 0; i < size; i++) {
				com = Component.VWIDGETARRAY.get(i);
				if (com instanceof LPDigitPasswordTextField) {
					lpdptf = (LPDigitPasswordTextField) com;
					/*<input type='password'  encryptMode='01' alertName='交易密码' 
						style="-wap-input-format: 'N'; -wap-input-required: 'true'" 
							isRandomPass='true' class='inputText' 
								name='password' minleng='6' maxleng='6' ></input>*/
					type = (String) lpdptf.getPropertyByName("type");
					if (null != type && type.equalsIgnoreCase("password")) {
						String name = lpdptf.getPropertyByName("name");
						String isRandomPass = lpdptf.getPropertyByName("isRandomPass");
						if ("password".equals(name) && "true".equals(isRandomPass)) {
							result = lpdptf.getText(); 
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	protected StringBuffer getBuffFromForm(Component comp, StringBuffer buf, String action, Task task) {
		// TODO Auto-generated method stub
		try {
			if (comp instanceof LPTextField) {
				LPTextField ltf = (LPTextField) comp;
				buf.append(ltf.getPropertyByName("name"));
				buf.append("=");
				String value = ltf.getContentText().trim();
				// 如果这个输入框是日期输入框，那么值应该取其value的属性值。
				if(((MyLPTextField) ltf.realView_).isDateField_ == true){
					value = ltf.getPropertyByName("value");
				}
				if(!((MyLPTextField) ltf.realView_).getSubValue().equals("")){
					value =((MyLPTextField) ltf.realView_).getSubValue();
				}
				buf.append(Utils.escapeURIComponent(encryptValue((String) ltf.getPropertyByName("encryptMode"), value, task)));
				buf.append("&");
			} else if (comp instanceof LPDateField) {
				LPDateField ltf = (LPDateField) comp;
				buf.append(ltf.attrName_);
				buf.append("=");
				String value = ltf.getContentText().trim();
				if (null == value || value.equals("")) {
					buf.append(value);
					buf.append("&");
				} else {
					value = Utils.adjustDate(value);
					buf.append(Utils.escapeURIComponent(encryptValue((String) ltf.getPropertyByName("encryptMode"), value, task)));
					buf.append("&");
				}
			} else if ((comp instanceof LPCheckBox && ((LPCheckBox) comp).isChecked())) {
				LPCheckBox lpcb = (LPCheckBox) comp;
				buf.append(lpcb.getPropertyByName("name"));
				String value = lpcb.getPropertyByName("value").trim();
				buf.append("=");
				if (value == null) {
					value = "";
				}
				buf.append(Utils.escapeURIComponent(encryptValue((String) lpcb.getPropertyByName("encryptMode"),value, task)));
				buf.append("&");
			} else if ((comp instanceof LPRadio && ((LPRadio) comp).isChecked())) {
				LPRadio lpcb = (LPRadio) comp;
				buf.append(lpcb.getPropertyByName("name"));
				buf.append("=");
				String value = lpcb.getPropertyByName("value").trim();
				if (value == null) {
					value = "";
				}
				buf.append(Utils.escapeURIComponent(encryptValue((String) lpcb.getPropertyByName("encryptMode"),value, task)));
				buf.append("&");
			} else if (comp instanceof LPSelect) {
				// LPSelect lps = (LPSelect) comp;
				// buf.append(lps.getPropertyByName("name"));
				// buf.append("=");
				// buf.append(Utils.escapeURIComponent(encryptValue((String) lps.getPropertyByName("encryptMode"),
				// lps.attrValue_ != null ? lps.attrValue_:"", task)));
				// buf.append("&");
				LPSelect lps = (LPSelect) comp;
				String str = lps.attrValue_;
				if (str == null) {
					str = "";
				}
				buf.append(lps.getPropertyByName("name"));
				buf.append("=");
				buf.append(Utils.escapeURIComponent(encryptValue((String) lps.getPropertyByName("encryptMode"), str, task)));
				buf.append("&");

			} 
//			else if (comp instanceof LPLabel) {
//				LPLabel lplabel = (LPLabel) comp;
//				buf.append(lplabel.getPropertyByName("name"));
//				buf.append("=");
//				buf.append(Utils.escapeURIComponent(encryptValue((String) lplabel.getPropertyByName("encryptMode"),
//						lplabel.getPropertyByName("value").trim(), task)));
//				buf.append("&");
//			} 
			else if (comp instanceof LPHidden) {
				LPHidden lplabel = (LPHidden) comp;
				String name = lplabel.getPropertyByName("name");
				if ("preSignInfo".equals(name) && null != keyMobile.signResult && !"".equals(keyMobile.signResult)) {
					buf.append("sign");
					buf.append("=");
					buf.append(Utils.escapeURIComponent(keyMobile.signResult));
				} else {
					buf.append(name);
					buf.append("=");
					buf.append(Utils.escapeURIComponent(encryptValue((String) lplabel.getPropertyByName("encryptMode"), (String) lplabel
							.getPropertyByName("value"), task)));
				}
				buf.append("&");

			} else if (comp instanceof LPDigitPasswordTextField) {  //密码键盘
				LPDigitPasswordTextField lpd = (LPDigitPasswordTextField) comp;
				buf.append(lpd.getPropertyByName("name"));
				buf.append("=");
				String value = lpd.getContentText().trim();
				buf.append(Utils.escapeURIComponent(encryptValue((String) lpd.getPropertyByName("encryptMode"), value, task)));
				buf.append("&");
			} else if (comp instanceof LPSegment && ((LPSegment) comp).isChecked()) {
				LPSegment lpseg = (LPSegment) comp;
				buf.append(lpseg.getPropertyByName("name"));
				buf.append("=");
				buf.append(Utils.escapeURIComponent(encryptValue((String) lpseg.getPropertyByName("encryptMode"),
						lpseg.getPropertyByName("value").trim(), task)));
				buf.append("&");
			} else if (comp instanceof LPSwitchCopy && ((LPSwitchCopy) comp).isChecked()) {
				LPSwitchCopy lpswc = (LPSwitchCopy) comp;
				buf.append(lpswc.getPropertyByName("name"));
				buf.append("=");
				buf.append(Utils.escapeURIComponent(encryptValue((String) lpswc.getPropertyByName("encryptMode"),
						lpswc.getPropertyByName("value").trim(), task)));
				buf.append("&");
			}else if (comp instanceof LPLottery) {
				LPLottery lottery = (LPLottery) comp;
				buf.append(lottery.getSubmitValue());
				buf.append("&");
			} else if (comp instanceof LPMovieTicket) {
				LPMovieTicket movieTicket = (LPMovieTicket) comp;
				buf.append(movieTicket.getPropertyByName("name"));
				buf.append("=");
				buf.append(Utils.escapeURIComponent(encryptValue(
						(String) movieTicket.getPropertyByName("encryptMode"),
						movieTicket.getPropertyByName("value").trim(), task)));
				buf.append("&");
			} else if(comp instanceof LPCityChooser){
				LPCityChooser cityChooser = (LPCityChooser) comp;
				buf.append(cityChooser.getPropertyByName("name"));
				buf.append("=");
				buf.append(Utils.escapeURIComponent(encryptValue(
						(String) cityChooser.getPropertyByName("encryptMode"),
						cityChooser.getPropertyByName("value").toString(), task)));
				buf.append("&");
			} else if (comp instanceof LPSegmentLayout) {
				LPSegmentLayout segmentLayout = (LPSegmentLayout) comp;
				int segmentSize = segmentLayout.segmentList_.size();
				if (segmentSize > 0) {
					buf.append(segmentLayout.segmentList_.get(0)
							.getPropertyByName("name"));
					buf.append("=");
					for (int i = 0; i < segmentLayout.segmentList_.size(); i++) {
						if (segmentLayout.segmentList_.get(i).isChecked()) {
							buf.append(Utils.escapeURIComponent(encryptValue(
									(String) segmentLayout.segmentList_.get(i)
											.getPropertyByName("encryptMode"),
									segmentLayout.segmentList_.get(i)
											.getPropertyByName("value").trim(),
									task)));
							break;
						}
					}
					buf.append("&");
				}
			}
			// 有些业务需要提交submit按钮的name和value。
			else if(comp instanceof com.bankcomm.ui.specialwidget.LPButton){
				com.bankcomm.ui.specialwidget.LPButton submitButton =
						(com.bankcomm.ui.specialwidget.LPButton) comp;
				if(submitButton.getPropertyByName("needsubmit") != null
						&& "true".equals(submitButton.getPropertyByName("needsubmit"))
						&& submitButton.isPressed_ == true){
					String attrName = (String) comp.getPropertyByName("name");
					if (attrName != null) {
						buf.append(attrName);
						buf.append("=");
						buf.append(Utils.escapeURIComponent(encryptValue(
								(String) comp.getPropertyByName("encryptMode"),
								(String) (comp.getPropertyByName("value")), task)));
						buf.append("&");
					}
					submitButton.isPressed_ = false; // 置点击状态为false。
				}
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
		return buf;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		 Component.ACTIONV = null;
        //当该Activity销毁时调用释放资源
        View decorView = this.getWindow().getDecorView();  
        release(decorView);
        
        Utils.releaseObject(LPRadio.checkedImg_);
        Utils.releaseObject(LPRadio.unCheckedImg_);
        
        if(ConfigManager.currentView_ != null && ConfigManager.currentView_ == this){
        	Utils.printOutToConsole("当前currentView是EMPView。");
        	ConfigManager.currentView_ = null;
        }
        
        if (decorView instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) decorView;
            vg.removeAllViews();
        }
        
        //清理缓存图片
        if(null != Utils.getAsyncImageLoader()){
        	Utils.getAsyncImageLoader().cacheMap.clear();
        	System.gc();
        }
	}

	@Override
	public void setContentView(View view) {
		//当栈里没有内容或者是只有一个对象时，不作资源释放，在onDestory中做释放，避免小i跳转后重复释放
		if(null != Component.ACTIONV && Component.ACTIONV.size() > 1){
			// 以下两行是释放资源的方法。在页面转换的时候释放上个页面view的资源，以释放内存
			View decorView = this.getWindow().getDecorView();  
			release(decorView);  
		}
		super.setContentView(view);	
	}
	
	 // 释放资源。
    public void release(View view) {
        if (view instanceof ViewGroup) {
            ViewGroup vg = (ViewGroup) view;
            for (int j = 0; j < vg.getChildCount(); j++) {
                View Layout = vg.getChildAt(j);
                if (Component.VWIDGETARRAY == null || Component.VWIDGETARRAY.size() == 0)
                    return;
                Component c = (Component) getComponent(Layout); // c是component对象。
                if (c != null) {
                    releaseResource(c); 
                } else {
                    release(Layout); // c不是component对象，递归找它的子控件。                  
                }                   
            }
        }
    }

    // 拿到component。
    public Component getComponent(Object v) {
        if (v instanceof CompositedComponent) {
            CompositedComponent cc = (CompositedComponent) v;
            return cc.composited();
        }
        return null;
    }

    // 释放资源。
	public void releaseResource(Component component) {
        View view = component.realView_;
        if (view instanceof AbsoluteLayout) {
            AbsoluteLayout ll = (AbsoluteLayout) view;
            final int size = ll.getChildCount();
            View v = null;
            for (int i = 0; i < size; i++) {
                v = ll.getChildAt(i);
                Component c = (Component) getComponent(v);
                if(c != null){
                    c.releaseResource(c);
                }
                c = null;
            }
        }
        
        if (null != component.focusImg_ && !component.focusImg_.isRecycled()) {
            component.focusImg_.recycle();
        }
        component.focusImg_ = null;
        if (null != component.unFocusImg_ && !component.unFocusImg_.isRecycled()) {
            component.unFocusImg_.recycle();
        }
        component. unFocusImg_ = null;
        if (null != component.property_)
            component. property_.clear();
        component. property_ = null;
        component.parent_ = null;
        component.parentComponent_ = null;
        component. attributes_ = null;
    }
	
	/**
	 * 为系统自带按键做逻辑处理
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Object[] args = null;
		LuaObject lua = null;
		try {
			switch (keyCode) {
			case KeyEvent.KEYCODE_BACK:
				// 返回取消定时
				if (LuaTimer.timer_ != null) {
					LuaTimer.timer_.cancel();
				}
				if (null != Utils.keyHash_) {
					lua = Utils.keyHash_.get(LuaWindow.BACKSPACESTR);
					lua.call(args, 0);
				} else if(Component.ACTIONV != null && Component.ACTIONV.size() >= 2){//此处暂定  (缓存页面数量大于等于2)
					waitProgress = new WaitProgressDialog(ConfigManager.currentView_);
					waitProgress.show(null);
					handler.postDelayed(xmlRunnable,100);
				} else {
					super.onKeyDown(keyCode, event);
				}
				break;
			// 点击home按键改用广播监听，修正某些机型home键监听不到问题
			// case KeyEvent.KEYCODE_HOME:
			// if (null != LuaWindow.keyHash_) {
			// lua = LuaWindow.keyHash_.get(LuaWindow.HOMESTR);
			// lua.call(args, 0);
			// } else {
			// super.onKeyDown(keyCode, event);
			// }
			// // TODO Auto-generated catch block
			//
			// break;
			default:
				return super.onKeyDown(keyCode, event);
			}
		} catch (Exception e) {
			Utils.printException(e);
		}
		return true;
	}

	private Runnable xmlRunnable = new Runnable() {
		@Override
		public void run() {
	        try {
	        	// TODO Auto-generated method stub
	        	int indexTemp = Component.ACTIONV.size() - 2; // 上一页的index。
	        	//获取栈顶页面
	        	String content = (String) Component.ACTIONV.get(indexTemp);
	        	Utils.printOutToConsole(content);
	        	//弹出当前页面
	        	Component.ACTIONV.pop();
	        	// 解析。
	        	AtomParser apc = new AtomParser(ConfigManager.currentView_, AtomParser.ENTIRE);
	        	content = Utils.unescapeHTML(content);
	        	content = Utils.insteadOfSpecillCharacter(content, true);
	    		android.util.Xml.parse(content.trim(), apc);
	    		ConfigManager.currentView_.runOnUiThread(new Runnable() {
	    			@Override
	    			public void run() {
	    				if(null != waitProgress && null != waitProgress.dialog_){
	    					waitProgress.dialog_.dismiss();
	    					waitProgress = null;
	    				}
	    				ConfigManager.currentView_.setContentView(ComponentCopy.COMPONENT.getLPView());
	    			}
	    		});
	    	} catch (Exception e){
	    		if(ConfigManager.currentView_ != null &&
	    				!ConfigManager.currentView_.isFinishing()){
	    			ConfigManager.currentView_.runOnUiThread(new Runnable() {
	    				@Override
	    				public void run() {
	    					if(null != waitProgress && null != waitProgress.dialog_){
	    						waitProgress.dialog_.dismiss();
	    						waitProgress = null;
	    					}
	    				}
	    			});
	    		}
	    	}
		}
	};
	
	/**
	 * 初始化lua脚本，将脚本中对应的window、screen或者document节点映射到相应的对象
	 */
	public static void initLuaScript() {
		LuaLib lualib_ = new LuaLib();
	}

	/**
	 * 读取本地文件main.xml，根据该文件显示界面内容，并决定程序的下一步动作
	 */
	private void readMainXml() {
		// TODO Auto-generated method stub
		String mainXml;
		initLuaScript();
		if (UNITTESTFLAG) {
			// 单元测试界面
			mainXml = Utils.getStringFormAsset(this, "unit_main.xml");
			LuaHistory.add(mainXml);
		} else {
			mainXml = Utils.getStringFormAsset(this, "main.xml");
		}

		AtomParser apc = new AtomParser(this, AtomParser.ENTIRE);
		try {
			android.util.Xml.parse(mainXml, apc);
			setContentView(ComponentCopy.COMPONENT.getLPView());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
	}
	
	public String NotNuLLCtrl(LPLayout form) {
		int size = form.getCompChildCount();
		String isTrue = "";
		for (int i = 0; i < size && isTrue.equals(""); i++) {
			Object v = form.getCompChildAt(i);
			
			if (v instanceof LPLayout) {
				if (((LPLayout) v).visible() == View.VISIBLE) {
					isTrue = isTrue.concat(NotNuLLCtrl((LPLayout) v));
				} else {
					continue;
				}
			} else if (v instanceof LPDigitPasswordTextField) {
				if (((LPDigitPasswordTextField) v).visible() == View.VISIBLE) {
					String str = ((LPDigitPasswordTextField) v).getIsNotNull();
					String text = ((LPDigitPasswordTextField) v)
							.getContentText().trim();
					String alert = !((LPDigitPasswordTextField) v).getAlertStr().equals("") ? ((LPDigitPasswordTextField) v)
							.getAlertStr()
							: getString(R.string.checktext);
					int length = ((EditText) (((LPDigitPasswordTextField) v).realView_))
							.getText().toString().length();
					int minleng = ((LPDigitPasswordTextField) v).minLeng();
					if (str.equals("true") && (text == null || text.equals(""))) {
						LPToastUtil.getInstance().getToast(
								alert + getString(R.string.isnotnull), this);
						isTrue = isTrue.concat("true");
					}
					else if (length < minleng) {
						LPToastUtil.getInstance().getToast(
								alert + getString(R.string.not_less_than)
								+ minleng + getString(R.string.digit), this);
						isTrue = isTrue.concat("true");

					}
				}
			} else if (v instanceof LPTextField) {
				if (((LPTextField) v).visible() == View.VISIBLE) {
					String str = ((LPTextField) v).getIsNotNull();
					String text = ((LPTextField) v).getContentText().trim();
					String alert = !((LPTextField) v).getAlertStr().equals("") ? ((LPTextField) v)
							.getAlertStr()
							: getString(R.string.checktext);
					int length = ((EditText) (((LPTextField) v).realView_))
							.getText().toString().length();
					int minleng = ((LPTextField) v).minLeng();
					if (str.equals("true") && (text == null || text.equals(""))) {
						LPToastUtil.getInstance().getToast(
								alert + getString(R.string.isnotnull), this);
						isTrue = isTrue.concat("true");
					}else if (length < minleng) {
						LPToastUtil.getInstance().getToast(
								alert + getString(R.string.not_less_than)
										+ minleng + getString(R.string.digit),
								this);
						isTrue = isTrue.concat("true");
					}
				}
			}
			// ADD BY ZHAOBIN 设置电影票不能为空
			else if (v instanceof LPMovieTicket) {
				LPMovieTicket ticket = (LPMovieTicket) v;
				String value = ticket.getPropertyByName("value").trim();
				if (value.equals("")) {
					LPToastUtil.getInstance().getToast(
							getString(R.string.movie_noselectwarning), this);
					isTrue = isTrue.concat("true");
				}
			}
		}
		return isTrue;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		// 扫描二维码不回显
		 if (requestCode == SCAN_SUBMIT_CODE) {
		  handleScanSubmitResult(resultCode, data);
		 }

		if (requestCode == SCAN_RESHOW_CODE) {
			handleScanShowResult(resultCode, data);
		}

		if (requestCode == IMAGE_PICKER_REQUEST_CODE) {
			if (resultCode == Activity.RESULT_OK) {
				setImage(data);
			}
		}
		
		if(requestCode == SCAN_SEND_QRCODE_BY_GET){
			handleSendQRCodeBYGet(resultCode,data);
		}
		
	}

	public void handleJarEvent() {
		EventHandler uhandler = new EventHandler();
		uhandler.eventHandler = new Handler() {
			public void handleMessage(Message msg) {
				if (null != msg
						&& msg.what == EventHandler.MSG_QRCORD_SCAN_SHOW_TEXT) {
					scanTextField = (MyLPTextField) msg.obj;
					gotoScan(EMPView.this, 1);
				}
				if (null != msg
						&& msg.what == EventHandler.MSG_READ_QRCODEIMAGE) {
					scanTextField = (MyLPTextField) msg.obj;
					intentToImagePicker();
				}

				if (null != msg
						&& msg.what == EventHandler.MSG_SAVE_QRCODEIMAGE) {
					if (LPMid.getInstance().QRBitMap != null) {
						storeInSD(LPMid.getInstance().QRBitMap,CODE_QRBITMAP);
						LPMid.getInstance().QRBitMap = null;
					}else{
						ArrayList list = Component.VWIDGETARRAY;
						for (int i = 0; i < list.size(); i++) {
							Object comp = list.get(i);
							if (comp instanceof LPImageItem) {
								LPImageItem image = (LPImageItem) comp;
								String isSave = image.getPropertyByName("save");
								if (!isSave.equals("")) {
									BitmapDrawable d = (BitmapDrawable) image.realView_
											.getBackground();
									Bitmap b = d.getBitmap();
									if (isSave.equals("image")) {
										storeInSD(b, CODE_TEMPIMAG);
									} else if (isSave.equals("voucher")) {
										storeInSD(b, CODE_FAVIMAG);
									}
								}
							}
						}
					}
				}
				
				if (null != msg
						&& msg.what == EventHandler.MSG_SUBMIT_QRCODE) {
					scanButton=(com.rytong.tools.ui.LPButton)msg.obj;
					ArrayList list = Component.VWIDGETARRAY;
					for (int i = 0; i < list.size(); i++) {
						Object comp = list.get(i);
						if (comp instanceof LPHidden) {
							LPHidden scanhidden = (LPHidden) comp;
							String str=scanhidden.getPropertyByName("scan");
							if(!str.equals("") && str.equals("true")){
								scanHiddenField=scanhidden;
								break;
							}
						}
					}
					gotoScan(EMPView.this, 0);
				}
				
				if (null != msg && msg.what == EventHandler.MSG_LUA_SEND_QRCODE) {
					Bundle data=msg.getData();
					qrUrl=data.getString("qrUrl");
					qrParm=data.getString("qrParmName");
					gotoScan(EMPView.this, 2);
				}

				//新增基金搜索
				if(null != msg && msg.what == EventHandler.MSG_SEARCH_JIJIN){
					Bundle data = msg.getData() ;
					searchURL = data.getString("searchurl");
					searchBODY = data.getString("searchbody")+"&n=MobileBank%3FtranCode%3DMB0460";
//					sendHttpInEMPView(searchURL,searchBODY);
					LPMid.getInstance().um_.sendHttpRequest(EMPView.this, searchURL, searchBODY);
				}
			}
		};
	}

	
	/**
	 * ADD BY ZHAOBIN START 2012.12.26 跳转扫描二维码界面
	 */
	public void gotoScan(BaseViewCopy bv, int id) {
		Intent intent = new Intent();
		intent.setClass(EMPView.this, CaptureActivity.class);
		switch (id) {
		case 0:
			bv.startActivityForResult(intent, SCAN_SUBMIT_CODE);
			break;

		case 1:
			bv.startActivityForResult(intent, SCAN_RESHOW_CODE);
			break;
        case 2:
			bv.startActivityForResult(intent, SCAN_SEND_QRCODE_BY_GET);
			break;
		}

	}

	public LPTextField.MyLPTextField scanTextField;
	public LPHidden scanHiddenField;
	public com.rytong.tools.ui.LPButton scanButton;

	// add by zhaobin start 2013-2-21
	/** 扫描二维码回显扫描值**/
	public void handleScanShowResult(int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			String contents = data.getStringExtra("code");
			// 扫描后提交数据
			if (scanTextField != null) {
				if(scanTextField.isNeedDecode){
					try {
						contents=DESCipher.doDecrypt(contents, "xytepfgn".getBytes());
						if(contents.contains("|")){
							String[] str=contents.split("\\|");
							scanTextField.setText(str[0]);
							scanTextField.setSubValue(contents);
						}
					} catch (Exception e) {
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								handleException("请扫描由手机银行生成的二维码!");
							}
						});
						return;
					}
				}else{
					scanTextField.setText(contents);	
				}
				
				
			}

		} else if (resultCode == RESULT_CANCELED) {
			LPToastUtil.getInstance().getToast(getString(R.string.result_failed_why),EMPView.this);
			if (scanTextField != null) {
				scanTextField.setText("");
			}
		}
	}
	
	public void keyBackPress() throws LuaException{
		Object[] args = null;
		LuaObject lua = null;
		if (null != Utils.keyHash_) {
			lua = Utils.keyHash_.get(LuaWindow.BACKSPACESTR);
			lua.call(args, 0);
		} else if(Component.ACTIONV != null && Component.ACTIONV.size() >= 2){//此处暂定  (缓存页面数量大于等于2)
			waitProgress = new WaitProgressDialog(ConfigManager.currentView_);
			waitProgress.show(null);
			handler.postDelayed(xmlRunnable,100);
		}else{
		  LPToastUtil.getInstance().isBranchBank=false;
		  finish();
		}
	}

	/** 扫描二维码不回显提交form**/
	public void handleScanSubmitResult(int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			String contents = data.getStringExtra("code");
			// 扫描后提交数据
			if (scanHiddenField != null) {
				scanHiddenField.setPropertyByName("value", contents);
				submit(scanButton);
			}
		} else if (resultCode == RESULT_CANCELED) {
			LPToastUtil.getInstance().getToast(
					getString(R.string.result_failed_why), EMPView.this);
			scanHiddenField = null;
			scanButton = null;
		}
	}
	 /** 扫描二维码发送get请求**/
	 public void handleSendQRCodeBYGet(int resultCode, Intent data){
		 if (resultCode == RESULT_OK) { 
			 String contents = data.getStringExtra("code");
			 String body = qrParm+"="+ Utils.escapeURIComponent(contents);
			 LPMid.getInstance().um_.sendHttpRequest(this, ConfigManager.SERVER_URI+qrUrl, body);
		 } else if (resultCode == RESULT_CANCELED) {
		    LPToastUtil.getInstance().getToast( getString(R.string.result_failed_why), EMPView.this);
		 }
	 }

	// add by zhaobin end

	// add by zhaobin begin 2013.7.4
	 /** 跳转到图片选择**/
	public void intentToImagePicker() {
		Intent intent = new Intent();
		intent.setAction("android.intent.action.GET_CONTENT");
		String type = "image/*";
		intent.setType(type);

		Intent wrapperIntent = Intent.createChooser(intent, null);
		EMPView.this.startActivityForResult(wrapperIntent, 0);
	}

	/** 从相册中读取图片**/
	public void setImage(Intent data) {
		try{
		Uri uri = data.getData();
		Cursor cursor = EMPView.this.getContentResolver().query(uri, null,
				null, null, null);
		cursor.moveToFirst();
		String path = cursor.getString(1).replace("/mnt", "");
		Utils.printOutToConsole(path);
		BitmapFactory.Options bfo = new BitmapFactory.Options();
		bfo.inSampleSize = 2;
		Bitmap bm = BitmapFactory.decodeFile(path, bfo);
		decodeImage(bm);
		cursor.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 解码图片并赋值 **/
	public void decodeImage(Bitmap bitmap) {
		MultiFormatReader multiFormatReader = new MultiFormatReader();

		// 解码参数
		Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>(
				2);

		// 解码类型，条形码，二维码等
		Vector<BarcodeFormat> decodeFormats = new Vector<BarcodeFormat>();
		if (decodeFormats == null || decodeFormats.isEmpty()) {
			decodeFormats = new Vector<BarcodeFormat>();
			decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
			decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
			decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
			decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
		}
		hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);
		// 设置编码格式，zxing中"UTF-8"为"UTF8"
		hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
		// 设置解析配置参数
		multiFormatReader.setHints(hints);

		// 结果
		Result rawResult = null;
		try {
			BitmapZxingResouce resouce = new BitmapZxingResouce(bitmap);
			Binarizer bin = new HybridBinarizer(resouce);
			BinaryBitmap bb = new BinaryBitmap(bin);
			rawResult = multiFormatReader.decodeWithState(bb);
			if (null != rawResult) {
				String contents = rawResult.getText();
				// result.setText("条码类型："+rawResult.getBarcodeFormat()+"\n内容："+rawResult.getText());;
				if (scanTextField != null) {
					if (scanTextField.isNeedDecode) {
						try {
							contents = DESCipher.doDecrypt(contents, "xytepfgn"
									.getBytes());
							if(contents.contains("|")){
								String[] str=contents.split("\\|");
								scanTextField.setText(str[0]);
								scanTextField.setSubValue(contents);
							}
						} catch (Exception e) {
							runOnUiThread(new Runnable() {

								@Override
								public void run() {
									handleException(getString(R.string.qrcodescanerror));
								}
							});
							return;
						}
					}else{
						scanTextField.setText(contents);	
					}
				}
			}

		} catch (Exception e) {
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					handleException(getString(R.string.qrcodescanerror));
				}
			});
		}
	}

	/** 保存图片**/
	private void storeInSD(Bitmap bitmap1,int type) {
		String SDPath = Environment.getExternalStorageDirectory()
				+ File.separator + "ebank_bocom" + File.separator;
		File file = new File(SDPath);
		if (!file.exists()) {
			file.mkdir();
		}
		File imageFile = new File(file, getFileName() + ".png");
		try {
			imageFile.createNewFile();
			FileOutputStream fos = new FileOutputStream(imageFile);
			bitmap1.compress(CompressFormat.PNG, 50, fos);
			switch (type) {
			case CODE_FAVIMAG:
				//存储优惠券
				handleException("优惠券已存至"+SDPath);
				break;
			case CODE_QRBITMAP:
				//存储二维码
				handleException(getString(R.string.qrsavenotice1)+SDPath+getString(R.string.qrsavenotice2));
				break;
			case CODE_TEMPIMAG:
				//存储普通图片
				handleException(SDPath);
				break;
			}
			
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			handleException(getString(R.string.qrcodenospaceerror));
		} catch (IOException e) {
			e.printStackTrace();
			handleException(getString(R.string.qrcodenospaceerror));
		}
		sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,Uri.parse("file://"+SDPath)));
	}

	public static String getCharacterAndNumber() {
		String rel = "";
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(System.currentTimeMillis());
		rel = "BOCM-"+formatter.format(curDate);
		return rel;
	}

	public String getFileName() {
		// mu
		// String fileNameRandom = getCharacterAndNumber(8);
		String fileNameRandom = getCharacterAndNumber();
		return fileNameRandom;
	}

	// add by zhaobin end
}
